<template>
  <div class="profile-container">
    <el-card class="profile-card">
      <div slot="header" class="card-header">
        <span>个人信息</span>
      </div>
      <el-form ref="profileForm" :model="profileForm" :rules="rules" label-width="100px">
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            method="post"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :headers="headers">
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="profileForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="profileForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="profileForm.phone"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleUpdate">保存修改</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { updateUser, updateAvatar, getInfo } from '@/api/user'

export default {
  name: 'Profile',
  data() {
    return {
      profileForm: {
        username: '',
        email: '',
        phone: '',
        nickname: '',
        avatar: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ]
      },
      loading: false,
      uploadUrl: 'http://localhost:8081/api/files/upload'
    }
  },
  computed: {
    ...mapState({
      userInfo: state => state.user.userInfo
    }),
    headers() {
      return {
        Authorization: `Bearer ${this.$store.state.user.token}`
      }
    }
  },
  created() {
    this.fetchUserData()
  },
  methods: {
    // 获取用户数据
    fetchUserData() {
      this.loading = true
      getInfo()
        .then(response => {
          console.log('获取到的用户信息:', response.data)
          if (response.data) {
            // 复制所有用户数据，确保包含所有字段
            this.profileForm = { ...response.data }
            
            // 如果头像路径是相对路径，添加服务器前缀
            if (this.profileForm.avatar && !this.profileForm.avatar.startsWith('http')) {
              const baseUrl = 'http://localhost:8081'
              this.profileForm.avatar = baseUrl + this.profileForm.avatar
              console.log('处理后的头像URL:', this.profileForm.avatar)
            }
          } else {
            // 如果直接API请求失败，则尝试使用Vuex中缓存的用户信息
            this.initForm()
          }
        })
        .catch((error) => {
          // 如果API请求出错，尝试使用Vuex中缓存的用户信息
          console.error('获取用户信息失败:', error)
          this.initForm()
        })
        .finally(() => {
          this.loading = false
        })
    },
    // 使用Vuex中的用户信息初始化表单
    initForm() {
      if (this.userInfo) {
        this.profileForm = { ...this.userInfo }
      } else {
        // 如果Vuex中也没有用户信息，则重新获取
        this.$store.dispatch('user/getInfo')
          .then(data => {
            this.profileForm = { ...data }
          })
      }
    },
    handleUpdate() {
      this.$refs.profileForm.validate(valid => {
        if (valid) {
          this.loading = true
          // 确保用户ID存在
          if (!this.profileForm.id) {
            this.$message.error('获取用户ID失败，请刷新页面重试')
            this.loading = false
            return
          }
          
          // 确保包含所有必要字段
          const updateData = {
            id: this.profileForm.id,
            username: this.profileForm.username,
            email: this.profileForm.email,
            phone: this.profileForm.phone,
            avatar: this.profileForm.avatar,
            // 确保表单初始化时有这些值，否则从userInfo中获取
            role: this.profileForm.role || (this.userInfo && this.userInfo.role),
            status: this.profileForm.status || (this.userInfo && this.userInfo.status) || 1
          }
          
          console.log('准备提交的用户数据:', updateData)
          
          updateUser(this.profileForm.id, updateData)
            .then((response) => {
              console.log('更新用户信息成功:', response)
              this.$message.success('个人信息更新成功')
              // 重新获取用户信息
              this.$store.dispatch('user/getInfo')
                .then(() => {
                  this.fetchUserData() // 刷新表单数据
                })
            })
            .catch(error => {
              console.error('更新个人信息失败:', error)
              this.$message.error('更新个人信息失败: ' + (error.message || '请稍后重试'))
            })
            .finally(() => {
              this.loading = false
            })
        }
      })
    },
    handleAvatarSuccess(response) {
      console.log('上传成功响应数据:', response)
      
      // 处理返回的图片路径，确保是完整的URL
      let imageUrl = response.data
      
      // 如果返回的是相对路径，拼接完整URL
      if (imageUrl && !imageUrl.startsWith('http')) {
        const baseUrl = 'http://localhost:8080' // 替换为您的实际后端地址
        imageUrl = baseUrl + imageUrl
      }
      
      console.log('处理后的图片URL:', imageUrl)
      this.profileForm.avatar = imageUrl
      this.$message.success('头像上传成功，修改已保存')
      
      // 只更新头像，不自动提交到服务器
      // 避免因为必填字段验证导致的错误
      // 需要用户点击保存修改按钮统一提交所有更改
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    }
  }
}
</script>

<style lang="scss" scoped>
.profile-container {
  padding: 20px;

  .profile-card {
    max-width: 800px;
    margin: 0 auto;

    .card-header {
      font-size: 18px;
      font-weight: bold;
    }

    .avatar-uploader {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      width: 178px;
      height: 178px;

      &:hover {
        border-color: #409EFF;
      }

      .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
      }

      .avatar {
        width: 178px;
        height: 178px;
        display: block;
      }
    }
  }
}
</style> 